import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTaskActionCreator } from '../store';

export default function Header() {
  // 5.1 声明state
  const [task, setTask] = useState('');
  const dispatch = useDispatch();

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      // 5.5 通过dispatch触发新增action
      dispatch(addTaskActionCreator(task));
      setTask('');
    }
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        // 5.2 设置value和onChange
        value={task}
        onChange={(e) => setTask(e.target.value)}
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
